﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using RonYee.Models;
using RonYee.Service;

namespace RonYee.Controllers
{
    public class FilesController : Controller
    {
        RongeDb db = new RongeDb();
        //
        // GET: /Files/
        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Index()
        {
            var file = from f in db.Files select f;
            return View(file.ToList());
        }

        [Authorize(Roles = "Admin,Editer")]
        [HttpPost]
        public ActionResult Upload() 
        {
            foreach (string upload in Request.Files) 
            {
                string path = null;
                string fileOldName = "";
                string extension = "";
                string filename = "";
                string fileNewName = "";

                if (!RonYee.Service.HasFiles.HasFile(Request.Files[upload])) continue;
                string createPath = AppDomain.CurrentDomain.BaseDirectory + @"FilesPool\Files";
                path = HasFolders.HasFolder(createPath);
                fileOldName = Path.GetFileName(Request.Files[upload].FileName);
                extension = System.IO.Path.GetExtension(fileOldName);//扩展名 ".xxx"
                Stream fileStream = Request.Files[upload].InputStream;
                filename = Path.GetFileName(Request.Files[upload].FileName);

                fileNewName = RandomNumberTo.RandomNumberToName() + extension;
                Request.Files[upload].SaveAs(Path.Combine(path, fileNewName));

                var files = new RonYee.Models.File()
                {
                    NewsId=1,
                    FileName=filename,
                    FileMineType=extension,
                    FileUrl = Path.Combine(path, fileNewName),
                    AddTime=DateTime.Now,
                    EditUser=HttpContext.User.Identity.Name.ToString(),
                   // EditUser=HttpContext.User.Identity.Name,
                    FileType1 = Convert.ToInt32(Request.Form["FileType1.Value"]) 

                };
                db.Files.Add(files);
                db.SaveChanges();
                
            }
            return RedirectToAction("Index");
        }
        //文件列表页
        public ActionResult List() 
        {
            var list = db.Files.ToList();
            return View(list);
        }

        //文件下载页
        public FilePathResult Download(int id) 
        {
            var fileinfo = db.Files.Find(id);
            return File(fileinfo.FileUrl, fileinfo.FileMineType, fileinfo.FileName);
        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Details(int id)
        {
            RonYee.Models.File file = db.Files.Find(id);
            if (file == null)
                return RedirectToAction("Index");
            return View("Details", file);
        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Create()
        {
            return View();
        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Edit(int id)
        {
            RonYee.Models.File file = db.Files.Find(id);
            if (file == null)
            {
                return RedirectToAction("Index");
            }
            return View(file);
        }

        [Authorize(Roles = "Admin,Editer")]
        [HttpPost]
        public ActionResult Edit(RonYee.Models.File model)
        {
            try
            {
                var file = db.Files.Find(model.FileId);
                UpdateModel(file);
                db.SaveChanges();
                return RedirectToAction("Details", new { id = model.FileId });
            }
            catch (Exception e)
            {
                ModelState.AddModelError("", "修改失败，请查看详细错误信息:" + e);
            }
            return View(model);

        }

        [Authorize(Roles = "Admin,Editer")]
        public ActionResult Delete(int id)
        {
            RonYee.Models.File file = db.Files.Find(id);
            if (file == null)
                return RedirectToAction("Index");
            return View(file);
        }

        [Authorize(Roles = "Admin,Editer")]
        [HttpPost]
        public RedirectToRouteResult Delete(int id, FormCollection collection)
        {   
            var file = db.Files.Find(id);

            //删除物理文件
            var delThis = (from d in db.Files
                          where d.FileId == id
                          select d).FirstOrDefault();
            
            System.IO.File.Delete(delThis.FileUrl);

            //删除数据库条目
            db.Files.Remove(file);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

    }

}
